package cn.example.demo.common.db.handler;

import cn.example.demo.common.db.pojo.entity.BaseEntity;
import cn.example.demo.common.secure.context.LoginContext;
import cn.example.demo.common.secure.dto.LoginUser;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * <p>
 *
 * </p>
 *
 * @author Lizuxian
 * @create 2022/4/16 15:27
 */
@Slf4j
public class CustomMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        LoginUser sysUser = LoginContext.singleton().getCurrentLoginUser();
        if (sysUser != null) {
            setFieldValByName(BaseEntity.Fields.organizationId, sysUser.getDeptId(), metaObject);
            setFieldValByName(BaseEntity.Fields.createUser, sysUser.getUserId(), metaObject);
            setFieldValByName(BaseEntity.Fields.createUserName, sysUser.getRealName(), metaObject);
            setFieldValByName(BaseEntity.Fields.createTime, new Date(), metaObject);
        } else {
            setFieldValByName(BaseEntity.Fields.organizationId, -9, metaObject);
            setFieldValByName(BaseEntity.Fields.createUser, -1, metaObject);
            setFieldValByName(BaseEntity.Fields.createUserName, "未认证用户", metaObject);
            setFieldValByName(BaseEntity.Fields.createTime, new Date(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LoginUser sysUser = LoginContext.singleton().getCurrentLoginUser();
        if (sysUser != null) {
            setFieldValByName(BaseEntity.Fields.updateUser, sysUser.getUserId(), metaObject);
            setFieldValByName(BaseEntity.Fields.updateUserName, sysUser.getRealName(), metaObject);
            setFieldValByName(BaseEntity.Fields.updateTime, new Date(), metaObject);
        } else {
            setFieldValByName(BaseEntity.Fields.updateUser, -1, metaObject);
            setFieldValByName(BaseEntity.Fields.updateUserName, "未认证用户", metaObject);
            setFieldValByName(BaseEntity.Fields.updateTime, new Date(), metaObject);
        }
    }
}
